package org.lq.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.junit.Test;

public class JDBCUtil {
	
	private static final String DRIVER = "com.mysql.jdbc.Driver";
	private static final String URL = "jdbc:mysql://localhost:3306/jdbc";
	private static final String USER = "root";
	private static final String PASSWORD = "root";
	static {
		try {
			Class.forName(DRIVER);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
	public static Connection getConn() {
		Connection conn = null;
		try {
			conn = DriverManager.getConnection(URL,USER,PASSWORD);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}
	
	
	public static void closeAll(ResultSet rs,PreparedStatement ps,Connection conn) {
		try {
			if(rs!=null) {
				rs.close();
				rs= null;
			}
			if(ps!=null) {
				ps.close();
				ps= null;
			}
			if(conn!=null) {
				conn.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 *  通用,添加,删除,修改方法
	 * @param sql 需要执行的SQL语句
	 * @param params SQL语句中的?赋值参数,按照?号顺序赋值
	 * @return 返回受影响行数
	 * @throws SQLException
	 */
	public static int executeUpdate(String sql,Object... params)throws SQLException {
		int num = 0;
		Connection conn = null;
		PreparedStatement ps = null;
		try {
			 conn = getConn();
			 ps = conn.prepareStatement(sql);
			if(params!=null) {
				for (int i = 0; i < params.length; i++) {
					ps.setObject(i+1, params[i]);
				}
			}
			num = ps.executeUpdate();
		} catch (Exception e) {
			throw e;
		}finally {
			closeAll(null, ps, conn);
		}
		return num;
	}
	
	
	// 泛型方法(当返回类型不确定的时候使用)
	
	/**
	 *  通用查询
	 * @param <T> 方法泛型
	 * @param sql SQL语句
	 * @param rco 对象创建接口
	 * @param param 参数
	 * @return 集合
	 * @throws SQLException
	 */
	public static <T> List<T> executeQuery(String sql,ResultSetCreateObject<T> rco,Object... param)throws SQLException{
		List<T> list = new ArrayList<T>();
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			conn = getConn();
			ps = conn.prepareStatement(sql);
			if(param!=null) {
				for (int i = 0; i < param.length; i++) {
					ps.setObject(i+1, param[i]);
				}
			}
			rs = ps.executeQuery();
			while(rs.next()) {
				T obj = rco.create(rs);
				list.add(obj);
			}
		} catch (Exception e) {
			throw e;
		}finally {
			JDBCUtil.closeAll(rs, ps, conn);
		}
		return list;
	}
	
	/*
	 *	  使用工具类完成单张表的CRUD操作
	 */
	

}
